import React, {useState} from "react";
import type {TreeProps} from 'antd';
import {Button, message, Tree} from "antd";
import {PlusOutlined} from "@ant-design/icons";
import {ModalForm, ProCard, ProFormText} from "@ant-design/pro-components";
import {useMenuTree} from "@/hooks/useMenuTree";
import {listMenu} from "@/pages/system/menu/api";
import {assignPermissions} from "@/pages/system/role/api";

interface IRoleAssign {
  role: API.IRole;
  triggerButton?: React.ReactElement;
}

export const RoleAssignModel: React.FC<IRoleAssign> = ({role, triggerButton}) => {
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>(['0-0-0', '0-0-1']);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>(['0-0-0']);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
  const {treeData, getMenuTree} = useMenuTree();

  const getRoleHasExistMenu = async () => {
    const {data} = await listMenu({
      roleId: role?.id
    })
    const hasExistMenu = data as API.IMenu[]
    const keys = hasExistMenu.map(item => item.id)
    setCheckedKeys(keys as any)
  }

  const onExpand: TreeProps['onExpand'] = (expandedKeysValue) => {
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  const onCheck: TreeProps['onCheck'] = async (checkedKeysValue) => {
    setCheckedKeys(checkedKeysValue as React.Key[]);
  };

  const onSelect: TreeProps['onSelect'] = (selectedKeysValue, info) => {
    setSelectedKeys(selectedKeysValue);
  };

  return (
    <ModalForm
      title={"分配权限"}
      width={550}
      initialValues={role}
      onFinish={async (values: API.IRole) => {
        const {success} = await assignPermissions(role?.id as string, checkedKeys as string[])
        if (success) {
          message.success("分配权限成功")
        } else {
          message.error("分配权限失败")
        }
        return success;
      }}
      autoFocusFirstInput
      trigger={triggerButton || <Button type="primary" icon={<PlusOutlined/>}> 分配权限</Button>}
      modalProps={{
        destroyOnClose: true,
        afterOpenChange: (open: boolean) => {
          if (open) {
            getRoleHasExistMenu();  // 只有在打开时才调用
          }
        },
      }}
    >
      <ProFormText
        disabled
        name="name" label="名称" placeholder="请输入角色名称"
        rules={[{required: true, message: '请输入角色名称'}]}/>
      <ProFormText
        disabled
        name="roleKey" label="权限字符串" placeholder="请输入权限字符串"
        rules={[{required: true, message: '请输入权限字符串'}]}
      />
      <ProCard
        title="权限列表"
        bordered
      >
        <Tree
          checkable
          onExpand={onExpand}
          expandedKeys={expandedKeys}
          autoExpandParent={autoExpandParent}
          onCheck={onCheck}
          checkedKeys={checkedKeys}
          onSelect={onSelect}
          selectedKeys={selectedKeys}
          treeData={treeData}
          checkStrictly={false}
        />
      </ProCard>
    </ModalForm>
  )
}
